package com.hqyj.realm;


import com.hqyj.pojo.Admin;

import com.hqyj.pojo.Manager;
import com.hqyj.service.AdminService;
import com.hqyj.service.managerService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;

import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;


/*
 *   认证域
 *   给shiro框架返回系统中用户的认证信息
 *   给shiro框架返回系统中用户的授权信息
 * */
public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    private AdminService adminService;

    @Autowired
    private managerService managerService;

    //给shiro框架返回系统中待认证用户的认证信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //使用认证令牌获取当前待登录的用户名
        String username = (String) token.getPrincipal();
        ByteSource saltBytes;
        SimpleAuthenticationInfo info;
        //在我们的系统中查询用户的认证信息
        Admin user = adminService.getOneByUsername(username);
        Manager user1 = managerService.getOneByUsername(username);

        //在shiro会话域中共享用户信息，以便业务层获取使用
        Session session = SecurityUtils.getSubject().getSession();
        if (user == null && user1 == null) {
            throw new UnknownAccountException(username + "不存在");
        } else if (user != null) {
            session.setAttribute("loginUser", user);
            //类型转换
            saltBytes = ByteSource.Util.bytes(user.getUserName());
//        使用四个参数的构造方法来构造认证信息
            info = new SimpleAuthenticationInfo(username, user.getPassword(), saltBytes, getName());
        } else {
            session.setAttribute("loginUser", user1);
            //类型转换
            saltBytes = ByteSource.Util.bytes(user1.getUserName());
//        使用四个参数的构造方法来构造认证信息
            info = new SimpleAuthenticationInfo(username, user1.getPassword(), saltBytes, getName());
        }


        return info;
    }


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
}
